package com.bzkj.framework.web.service;

import javax.annotation.Resource;

import com.bzkj.common.constant.CacheConstants;
import com.bzkj.common.constant.Constants;
import com.bzkj.common.constant.UserConstants;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.exception.ServiceException;
import com.bzkj.common.exception.user.*;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.MessageUtils;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.common.utils.ip.IpUtils;
import com.bzkj.framework.manager.AsyncManager;
import com.bzkj.framework.manager.factory.AsyncFactory;
import com.bzkj.framework.security.context.AuthenticationContextHolder;
import com.bzkj.system.service.ISysConfigService;
import com.bzkj.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.bzkj.common.core.redis.RedisCache;


import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    private static final String PDA = "PDA";

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String type) {

        // 验证码校验
        validateCaptcha(username, code, uuid, type);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                if (!StringUtils.equals(type, PDA)) {
                    recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
                    throw new UserPasswordNotMatchException();
                } else if (StringUtils.equals(type, PDA)) {
                    return "用户不存在/密码错误";
                }
            } else {
                if (!StringUtils.equals(type, PDA)) {
                    recordLoginInfo(username, Constants.LOGIN_FAIL, e.getMessage());
                    throw new ServiceException(e.getMessage());
                } else if (StringUtils.equals(type, PDA)) {
                    return e.getMessage();
                }
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        if (!StringUtils.equals(type, PDA)) {
            recordLoginInfo(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        }

        assert authentication != null;
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (StringUtils.equals(type, PDA)) {
            loginUser.setType("PDA");
        } else {
            recordLoginInfo(loginUser.getUserId());
        }
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid, String type) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (type != null && type.equals(PDA)) {
            captchaEnabled = false;
        }
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 根据用户昵称查询用户账号
     * 注意：存在多个用户时，返回用户账号列表，这时便需要提醒用户使用账号登录
     *
     * @param nickName 用户昵称
     */
    public String selectUserNameByNickName(String nickName) {
        List<String> userNames = userService.selectUserNameByNickName(nickName);
        if (userNames.size() > 1) {
            return "存在多个同名用户，请使用工号登录！";
        } else if (userNames.isEmpty()) {
            return "用户不存在/密码错误";
        }
        return userNames.get(0);
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   登录状态
     * @param message  登录信息
     */
    private void recordLoginInfo(String username, String status, String message) {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, status, message));
    }

    /**
     * 判断用户是否已超过设定范围但没修改过密码
     *
     * @param username 用户名
     * @return 查询结果
     */
    public Map<String, Integer> isPwdExpire(String username) {
        Map<String, Integer> resultMap = new HashMap<>();
        SysUser sysUser = userService.selectUserByUserName(username);

        // 如果用户的密码修改时间为空，直接返回
        if (sysUser == null || sysUser.getPwdTime() == null) {
            resultMap.put("flag", 1); // 需要修改密码
            resultMap.put("days", 0); // 无剩余天数
            return resultMap;
        }

        // 获取密码修改时间和当前日期
        LocalDate pwdDate = sysUser.getPwdTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate currentDate = LocalDate.now();

        // 获取设定的密码修改周期（默认3个月）
        int changeMonths = getChangeMonths();

        // 计算密码到期日期
        LocalDate expiryDate = pwdDate.plusMonths(changeMonths);

        // 判断是否已超过到期日期
        if (!currentDate.isBefore(expiryDate)) {
            resultMap.put("flag", 1); // 已过期，需要修改密码
            resultMap.put("days", 0); // 无剩余天数
        } else {
            resultMap.put("flag", 0); // 未过期
            // 计算剩余天数
            long days = ChronoUnit.DAYS.between(currentDate, expiryDate);
            resultMap.put("days", (int) days);
        }

        return resultMap;
    }

    /**
     * 获取密码修改周期（单位：月）
     *
     * @return 密码修改周期
     */
    private int getChangeMonths() {
        String changeMonthStr = configService.selectConfigByKey("change.password.month");
        if (changeMonthStr == null || changeMonthStr.isEmpty() || "0".equals(changeMonthStr)) {
            return 3; // 默认3个月
        }
        try {
            return Integer.parseInt(changeMonthStr);
        } catch (NumberFormatException e) {
            return 3; // 如果配置值无效，返回默认值
        }
    }


}
